<template>
  <div id="dictManage">
    <!-- <Breadcrumb content="动态表字典" /> -->
    <Splitpanes>
      <!-- 最左侧动态表字典  -->
      <Pane size="32">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">动态表字典</div>
            <vxe-input
              style="width: 130px"
              v-model="searchForm.searchValue"
              type="search"
              clearable
              class="vxeInputSearch"
              placeholder="关键字查询"
              @clear="findDictTableList"
              @keyup="keyupEnter"
              @search-click="handleSearch(searchForm.searchValue)"
            ></vxe-input>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-refresh"
              content="刷新"
              :loading="showLoading"
              @click="findDictTableList"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-square-plus"
              content="新建"
              @click="addDictTableDialog()"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-square-plus"
              content="设计模式"
              @click="showDictTableFiled()"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-square-plus"
              content="预览模式"
              @click="showDictTableData()"
            ></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="tableBox">
          <vxe-table
            ref="dictTableRef"
            class="mytable-scrollbar"
            border="inner"
            align="center"
            height="auto"
            :loading="showLoading"
            :data="dictTableList"
            :expand-config="{ expandAll: true, reserve: true }"
            @current-change="dictRowClick"
            :row-config="{ isCurrent: true, isHover: true }"
            :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }"
            resizable
            show-overflow
            keep-source
          >
            <vxe-column field="code" title="编码" width="220"> </vxe-column>
            <vxe-column field="name" title="名称"> </vxe-column>
            <vxe-column title="操作" width="90" align="center" fixed="right">
              <template #default="{ row }">
                <vxe-button
                  type="text"
                  status="primary"
                  icon="vxe-icon-edit"
                  circle
                  @click.native="editDictTableDialog(row)"
                  class="spanIcon"
                ></vxe-button>
                <vxe-button
                  type="text"
                  status="danger"
                  icon="vxe-icon-delete"
                  circle
                  @click.native="deleteDictTable(row)"
                  class="spanIcon"
                ></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

        <!-- 最左侧动态表字典弹框 -->
        <el-dialog
          :title="titleType()"
          :show-close="false"
          v-model="showDialog"
          append-to-body
          :close-on-click-modal="false"
          width="500px"
        >
          <el-form
            ref="dictTableFormRef"
            :model="dictTableForm"
            :rules="dictTableFormRule"
            label-width="100px"
            class="form-input-m"
            inline-message
            @reset="resetDictTableForm"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item prop="code" label="编码">
                  <el-input
                    type="text"
                    v-model="dictTableForm.code"
                    placeholder="请输入编码"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="name" label="名称">
                  <el-input
                    type="text"
                    v-model="dictTableForm.name"
                    placeholder="请输入名称"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="order" label="排序">
                  <el-input-number v-model="dictTableForm.sx" :min="1" :max="1000" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="dialog-footer flex right justify-end">
            <el-button type="primary" @click="saveDictTable('dictTableFormRef')">保存</el-button>
            <el-button @click="closeDialog('dictTableFormRef')">取消</el-button>
          </div>
        </el-dialog>
      </Pane>

      <!-- 中间设计模式  -->
      <Pane size="38" v-if="isDictTableFieldShow" class="designPane">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">设计模式</div>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-refresh"
              content="刷新"
              :loading="tLoading"
              @click="getDictTableFieldAndTableDataList"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-square-plus"
              content="设置字段"
              :loading="setFieldsLoading"
              @click="setTableColumnDialog()"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-save"
              :loading="saveFieldsLoading"
              content="保存"
              @click="saveDictTableFieldList"
            ></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="designTable">
          <vxe-table
            class="mytable-scrollbar"
            border="inner"
            align="center"
            ref="dictTableFieldRef"
            height="auto"
            :loading="tLoading"
            :row-config="{ isCurrent: true, isHover: true }"
            :data="dictTableFieldList"
            :column-config="{ resizable: true }"
            @current-change="tableFieldRowClick"
            :edit-config="{
              trigger: 'click',
              mode: 'cell',
              showIcon: false,
              showStatus: true
            }"
            :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }"
            resizable
            show-overflow
            keep-source
          >
            <vxe-column field="columnName" title="字段名" width="150"> </vxe-column>
            <vxe-column field="comments" title="字段描述" width="150"> </vxe-column>
            <vxe-column field="dataType" title="字段类型" width="150"> </vxe-column>
            <vxe-column field="columnId" title="字段顺序" width="80"> </vxe-column>
            <!-- <vxe-column field="isShow" title="是否展示" width="150"> </vxe-column> -->
            <!-- <vxe-column field="isEdit" title="是否编辑" width="150"> </vxe-column> -->
            <vxe-column field="isEdit" title="是否修改" width="120">
              <template #default="{ row, rowIndex, column }">
                <vxe-switch
                  v-model="row.isEdit"
                  open-label="是"
                  close-label="否"
                  open-value="0"
                  close-value="1"
                ></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column
              field="sx"
              title="顺序"
              width="80"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input v-model="row.sx" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="60" align="center" fixed="right">
              <template #default="{ row }">
                <vxe-button
                  type="text"
                  status="danger"
                  icon="vxe-icon-delete"
                  circle
                  @click.native="deleteDictTableField(row)"
                ></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

        <!-- 设置字段弹框  -->
        <el-dialog
          title="字段属性"
          :show-close="false"
          v-model="showTableColumnDialog"
          append-to-body
          :close-on-click-modal="false"
          width="800px"
        >
          <div class="setFieldsDialog">
            <vxe-table
              ref="tableColumnRef"
              class="mytable-scrollbar"
              border
              align="center"
              max-height="490px"
              :data="tableColumnList"
              :loading="setFieldsLoading"
              :row-config="{ isCurrent: true, isHover: true }"
              :column-config="{ resizable: true }"
              :checkbox-config="{
                labelField: 'name',
                checkMethod: checCheckboxkMethod2,
                visibleMethod: showCheckboxkMethod2
              }"
              resizable
              show-overflow
              keep-source
            >
              <vxe-column type="checkbox" width="50px" align="center"></vxe-column>
              <vxe-column field="columnName" title="字段名" width="150"> </vxe-column>
              <vxe-column field="comments" title="字段描述" width="150"> </vxe-column>
              <vxe-column field="dataType" title="字段类型" width="150"> </vxe-column>
              <vxe-column field="columnId" title="字段顺序" width="150"> </vxe-column>
            </vxe-table>

            <div class="setFieldsFooter flex right justify-end" style="margin-top: 10px">
              <el-button type="primary" @click="saveBatchTableField()">保存</el-button>
              <el-button @click="closeTableColumnDialog()">取消</el-button>
            </div>
          </div>
        </el-dialog>
      </Pane>

      <!-- 设计模式表单  -->
      <Pane size="30" v-if="isDictTableFieldShow">
        <div class="toolbartitle">组件属性</div>
        <el-form
          ref="tableFieldFormRef"
          :model="tableFieldForm"
          class="form-input-m"
          label-width="90px"
          inline-message
          v-loading="tLoading"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item prop="columnName" label="字段名">
                <el-input
                  type="text"
                  v-model="tableFieldForm.columnName"
                  placeholder="请输入字段名"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="comments" label="字段描述">
                <el-input
                  type="text"
                  v-model="tableFieldForm.comments"
                  placeholder="请输入字段描述"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="dataType" label="字段类型">
                <el-input
                  type="text"
                  v-model="tableFieldForm.dataType"
                  placeholder="请输入类型"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否修改" prop="isActive">
                <el-switch
                  v-model="tableFieldForm.isEdit"
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
                  active-value="0"
                  inactive-value="1"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="classify" label="组件类型">
                <el-radio-group v-model="tableFieldForm.classify">
                  <el-radio-button label="1" @click.prevent="changeCorrection('1')"
                    >标识</el-radio-button
                  >
                  <el-radio-button label="2" @click.prevent="changeCorrection('2')"
                    >表达式输入</el-radio-button
                  >
                  <el-radio-button label="3" @click.prevent="changeCorrection('3')"
                    >字典输入</el-radio-button
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="type" label="前缀类型">
                <el-select
                  v-model="tableFieldForm.prefixType"
                  filterable
                  placeholder="请选择规则类型"
                >
                  <el-option
                    v-for="typeObj in ruleTypeList"
                    :key="typeObj.code"
                    :label="typeObj.name"
                    :value="typeObj.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="prefixRule" label="前缀规则">
                <el-input type="text" v-model="tableFieldForm.prefix"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="infixType" label="中缀类型">
                <el-select
                  v-model="tableFieldForm.infixType"
                  filterable
                  placeholder="请选择规则类型"
                >
                  <el-option
                    v-for="typeObj in ruleTypeList"
                    :key="typeObj.code"
                    :label="typeObj.name"
                    :value="typeObj.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="infixRule" label="中缀规则">
                <el-input type="text" v-model="tableFieldForm.infix"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="suffixType" label="后缀类型">
                <el-select
                  v-model="tableFieldForm.suffixType"
                  filterable
                  placeholder="请选择规则类型"
                >
                  <el-option
                    v-for="typeObj in sufTypeList"
                    :key="typeObj.code"
                    :label="typeObj.name"
                    :value="typeObj.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="suffixRule" label="后缀规则">
                <el-input type="text" v-model="tableFieldForm.suffix"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="aotuNum" label="自增量">
                <el-input-number v-model="tableFieldForm.aotuNum" :min="1" :max="1000" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="prefix" label="前缀">
                <el-input
                  type="text"
                  v-model="tableFieldForm.prefix"
                  placeholder="请输入前缀"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="tableFieldForm.classify == '1'">
              <el-form-item prop="suffix" label="后缀">
                <el-input
                  type="text"
                  v-model="tableFieldForm.suffix"
                  placeholder="请输入后缀"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="24" v-if="tableFieldForm.classify == '2'">
              <el-form-item label="选择表达式" prop="expression">
                <el-select
                  placeholder="请选择表达式"
                  :teleported="false"
                  v-model="tableFieldForm.expression"
                  style="width: 200px" 
                >
                  <el-option
                    v-for="dict in cyhsDictList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.expression"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="选择字段"
                prop="correField"
                v-if="tableFieldForm.classify == '2'"
              >
                <el-select
                  placeholder="请选择字段"
                  :teleported="false"
                  v-model="tableFieldForm.correField"
                  style="width: 200px"
                >
                  <el-option
                    v-for="dict in dictTableFieldList"
                    :key="dict.id"
                    :label="dict.comments"
                    :value="dict.columnName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24" v-if="tableFieldForm.classify == '3'">
              <el-form-item label="选择字典" prop="dict">
                <el-select
                  placeholder="请选择字典"
                  :teleported="false"
                  v-model="tableFieldForm.dict"
                  style="width: 200px;"
                >
                  <el-option
                    v-for="dict in dictAllList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="order" label="排序">
                <el-input-number v-model="tableFieldForm.sx" :min="1" :max="1000" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="form-footer">
                <template #default>
                  <el-button type="primary" @click="saveTableField()">保存</el-button>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Pane>

      <!-- 预览模式 -->
      <Pane size="68" v-if="isTableDataShow" class="previewPane">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">预览模式</div>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-refresh"
              content="刷新"
              :loading="tpLoading"
              @click="getDictTableFieldAndTableDataList"
            ></vxe-button>
            <vxe-button
              type="text"
              class="button-blue"
              icon="vxe-icon-square-plus"
              content="添加数据"
              :loading="addPreDialogLoading"
              @click="addTableDataDialog()"
            ></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="previewTable">
          <vxe-table
            ref="detailTable"
            class="mytable-scrollbar"
            border
            align="center"
            height="auto"
            :data="tableDataList"
            :loading="tpLoading"
            :row-config="{ isCurrent: true, isHover: true }"
            :column-config="{ resizable: true }"
            resizable
            show-overflow
            keep-source
          >
            <vxe-column
              v-for="(item, index) in dictTableFieldList"
              :key="index"
              :field="item.columnName"
              :title="item.comments"
              width="120"
              :edit-render="{}"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row[item.code]" type="text"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column title="操作" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <vxe-button
                  type="text"
                  status="primary"
                  icon="vxe-icon-edit"
                  circle
                  @click.native="editTableData(row)"
                  class="spanIcon"
                ></vxe-button>
                <vxe-button
                  type="text"
                  status="danger"
                  icon="vxe-icon-delete"
                  circle
                  @click.native="deleteTableData(row)"
                  class="spanIcon"
                ></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

        <el-dialog
          title="数据"
          :show-close="false"
          v-model="showDataDialog"
          append-to-body
          :close-on-click-modal="false"
          width="800px"
          @close="closeDataDialog()"
        >
          <el-form
            ref="dataFormRef"
            :model="dataForm"
            label-width="110px"
            class="form-input-m"
            :inline-message="true"
          >
            <el-row>
              <el-col :span="12" v-for="(item, index) in dictTableFieldList" :key="index">
                <el-form-item :label="item.comments" :prop="item.columnName">
                  <vxe-select
                    v-model="dataForm[item.columnName]"
                    placeholder="可清除"
                    clearable
                    v-if="item.classify == '3' && item.isEdit == '0'"
                    @focus="getSecletDictDetailById(item)"
                  >
                    <vxe-option
                      v-for="(item, index) in selectDetailList"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></vxe-option>
                  </vxe-select>
                  <vxe-input
                    v-else-if="
                      dictTableFieldList.find((it) => it.classify == '2') &&
                      dictTableFieldList.find((it) => it.classify == '2').correField ==
                        item.columnName &&
                      item.isEdit == '0'
                    "
                    @change="getBdsResult(item.columnName, dataForm[item.columnName], dataForm)"
                    v-model="dataForm[item.columnName]"
                    type="text"
                  ></vxe-input>
                  <vxe-input
                    v-else-if="item.classify == '1' && item.isEdit == '0'"
                    v-model="dataForm[item.columnName]"
                    disabled
                    type="text"
                  ></vxe-input>
                  <el-input
                    v-else
                    type="text"
                    v-model="dataForm[item.columnName]"
                    :placeholder="'请输入' + item.comments"
                    clearable
                    :disabled="item.isEdit == '1' ? true : false"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="dialog-footer flex right justify-end">
            <el-button type="primary" @click="saveTableData()">保存</el-button>
            <el-button @click="closeDataDialog()">取消</el-button>
          </div>
        </el-dialog>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '../../stores/store';
import { funBdsJsResult } from '@/utils/Expression';

// 全局变量定义区 ==========
let isDictTableFieldShow = ref(true); //默认显示设计模式
let isTableDataShow = ref(false); //预览模式

// 加载状态
let showLoading = ref(false); //最左侧动态表字典
let tLoading = ref(false); //中间设计模式字段表格
let setFieldsLoading = ref(false); //设置字段弹框表格
let saveFieldsLoading = ref(false); //设计模式最上层保存按钮
let tpLoading = ref(false); //预览模式 刷新+表格
let addPreDialogLoading = ref(false); //预览模式添加数据弹框加载

// 弹框表单状态
let showDialog = ref(false); //最左侧动态表字典弹框
let showTableColumnDialog = ref(false); //中间设计模式 设置字段弹框
let showDataDialog = ref(false); //预览模式 添加数据弹框

let dictTableRef = ref(); //最左侧动态字典表格
let dictTableList: any = reactive([]); //最左侧动态字典表格数据
let tableColumnRef = ref(); //中间设置字段弹框里的表格ref
let tableColumnList: any = reactive([]); //设计模式 设置字段弹框表格数据
let dictTableFieldList: any = reactive([]); //设计模式表格数据
let tableDataList: any = reactive([]); //预览模式表格数据
let dataForm: any = reactive({}); //预览模式 弹框表单数据
let selectDetailList: any = reactive([]); //预览模式弹框 选择字典
let sltTable: any = {}; //接收动态字典表格当前行触发传来的row数据

// 屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 最左侧动态字典表 搜索关键字
let searchForm = {
  searchValue: ''
};

// 最左侧动态表弹框表单
let dictTableForm = reactive({
  id: null,
  code: '',
  name: '',
  sx: 0
});
// 最左侧动态表弹框表单校验
let dictTableFormRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 设计模式 最右侧表单
let tableFieldForm = reactive({
  id: null,
  pid: '',
  columnName: '',
  comments: '',
  dataType: '',
  columnId: '',
  isShow: '',
  isEdit: '',
  sx: 1,
  classify: '',
  aotuNum: 1,
  prefixType: '',
  prefix: '',
  infixType: '',
  infix: '',
  suffixType: '',
  suffix: '',
  expression: '',
  dict: '',
  correField: ''
});

// 设计模式表单:1：前缀 中缀类型
let ruleTypeList: any = [
  { code: 'gdz', name: '固定值' },
  { code: 'rqz', name: '日期值' }
];
// 设计模式表单 1：后缀类型
let sufTypeList: any = [{ code: 'seq', name: '自增序列' }];
//设计模式表单 2：选择表达式(首字母函数 全拼函数)
let cyhsDictList: any = reactive([]);
//设计模式表单 3：选择:字典
let dictAllList: any = reactive([]);

// 方法定义区 =============
onMounted(() => {
  findDictTableList(); //获取动态字典表列表
  getCyhsDictList(); //获取设计模式表单的选择表达式
  findAllDictList(); //获取设计模式表单的选择字典
});

// 获取动态字典表数据
function findDictTableList() {
  showLoading.value = true;
  dictTableList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/findDictTablePageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pageIndex: page.currentPage, pageSize: page.pageSize }
    })
    .then((res: any) => {
      dictTableList.push(...res.data.records);
      page.totalResult = res.data.total;
      dictRowClick({ row: dictTableList[0] }); //默认选中第一条数据
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取动态字典表列表失败',VxeNotifyType.error)
    });
}

// 查询/刷新
function handleSearch(row: string | number) {
  const url = '/api/sys/basDict/findDictPageList';
  dictTableList.length = 0;
  proxy.$http
    .get(url, { params: { seachValue: row, pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      dictTableList.push(...res.data.records);
      page.totalResult = res.data.total;
      dictRowClick({ row: dictTableList[0] }); //默认选中第一条数据
    })
    .catch((err: any) => {
      // VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}

// 点击最左侧动态字典表格当前行触发的事件
function dictRowClick({ row }: any) {
  (proxy.$refs.dictTableRef as any).setCurrentRow(row);
  sltTable = row;
  getDictTableFieldAndTableDataList(); // 获取动态字典表 设计模式字段数据+预览模式表格值
}

// 新建一级动态表字典
function addDictTableDialog() {
  dictTableForm.sx = page.totalResult + 1;
  showDialog.value = true;
}

// 判断动态表字典 弹框显示的标题
function titleType() {
  if (dictTableForm.id) {
    return `编辑动态表字典`;
  } else if (!dictTableForm.id) {
    return `新建动态表字典`;
  }
}

// 保存最左侧动态字典表弹框表单
function saveDictTable(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (dictTableForm.id === null) {
      const url = '/api/sys/basDictTable/addDictTable';
      const user = {
        code: dictTableForm.code,
        name: dictTableForm.name,
        sx: dictTableForm.sx
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          VxeMessage('新增动态字典成功', VxeNotifyType.success);
          clearForm();
          showDialog.value = false;
          findDictTableList(); //重新获取动态字典表数据
        })
        .catch((err: any) => {
          VxeMessage('新增动态字典失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/sys/basDictTable/editDictTable';
      const user = {
        id: dictTableForm.id,
        code: dictTableForm.code,
        name: dictTableForm.name,
        sx: dictTableForm.sx
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          VxeMessage('修改动态字典成功', VxeNotifyType.success);
          setTimeout(() => {
            clearForm();
            showDialog.value = false;
            findDictTableList(); //重新获取动态字典表数据
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('修改动态字典失败', VxeNotifyType.error);
        });
    }
  });
}

// 最左侧动态字典表弹框 取消
function closeDialog(formName: any) {
  let $ele = proxy.$refs[formName];
  $ele.clearValidate(); //移除校验结果
  clearForm();
  showDialog.value = false;
}

// 最左侧动态字典表弹框 清空表单
function clearForm() {
  dictTableForm.id = null;
  dictTableForm.code = '';
  dictTableForm.name = '';
  dictTableForm.sx = 0;
}
// 重置 最左侧动态表字典弹框表单
function resetDictTableForm(row: any) {
  if (IsEmpty(row)) {
    clearForm();
    return;
  }
  dictTableForm.id = null;
  dictTableForm.code = '';
  dictTableForm.name = '';
  dictTableForm.sx = 0;
}
// 点击设计模式按钮
function showDictTableFiled() {
  isDictTableFieldShow.value = true;
  isTableDataShow.value = false;
  proxy.$nextTick(() => {
    if (IsEmpty(dictTableFieldList.find((item) => item.id == tableFieldForm.id))) {
      tableFieldRowClick({ row: dictTableFieldList[0] }); //默认选中第一条数据
    } else {
      tableFieldRowClick({ row: dictTableFieldList.find((item) => item.id == tableFieldForm.id) }); //默认选中第一条数据
    }
  });
}
// 点击预览模式按钮
function showDictTableData() {
  isDictTableFieldShow.value = false;
  isTableDataShow.value = true;
}

// 最左侧动态表字典 当前行编辑小按钮
function editDictTableDialog(row: any) {
  dictTableForm.id = row.id;
  dictTableForm.code = row.code;
  dictTableForm.name = row.name;
  dictTableForm.sx = row.sx;
  showDialog.value = true;
}

// 最左侧动态字典表 当前行删除小按钮
function deleteDictTable(row: any) {
  proxy
    .$confirm('确定删除此字典？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/basDictTable/deleteDictTable';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 400) {
          VxeMessage('删除字典失败', VxeNotifyType.error);
        } else {
          findDictTableList();
          VxeMessage('删除字典成功', VxeNotifyType.success);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 中间获取动态字典表 设计模式字段数据+预览模式表格值
function getDictTableFieldAndTableDataList() {
  dictTableFieldList.length = 0;
  tableDataList.length = 0;
  tLoading.value = true;
  tpLoading.value = true;
  const url = '/api/sys/basDictTableField/getDictTableFieldAndTableDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltTable.id, tableName: sltTable.code }
    })
    .then((res: any) => {
      dictTableFieldList.push(...res.data.tableFieldList);
      tableDataList.push(...res.data.tableDataList);
      tableFieldRowClick({ row: dictTableFieldList[0] }); //默认选中第一条数据
      tLoading.value = false;
      tpLoading.value = false;
    })
    .catch((err: any) => {
      tLoading.value = false;
      tpLoading.value = false;
      // VxeMessage('获取数据失败',VxeNotifyType.error)
    });
}

// 点击设计模式当前行表格触发的事件
function tableFieldRowClick({ row }: any) {
  if (IsEmpty(row)) {
    clearTableFieldForm();
  } else {
    (proxy.$refs.dictTableFieldRef as any).setCurrentRow(row);
    setTableFieldForm(row);
  }
}
// 点击设计模式当前行表格触发的事件 清空右侧表单
function clearTableFieldForm() {
  tableFieldForm.id = null;
  tableFieldForm.pid = '';
  tableFieldForm.columnName = '';
  tableFieldForm.comments = '';
  tableFieldForm.dataType = '';
  tableFieldForm.columnId = '';
  tableFieldForm.isShow = '';
  tableFieldForm.isEdit = '';
  tableFieldForm.sx = 1;
  tableFieldForm.classify = '';
  tableFieldForm.aotuNum = 1;
  tableFieldForm.prefixType = '';
  tableFieldForm.prefix = '';
  tableFieldForm.infixType = '';
  tableFieldForm.infix = '';
  tableFieldForm.suffixType = '';
  tableFieldForm.suffix = '';
  tableFieldForm.expression = '';
  tableFieldForm.dict = '';
  tableFieldForm.correField = '';
}

// 点击设计模式当前行表格触发的事件 设置右侧表单
function setTableFieldForm(row: any) {
  tableFieldForm.id = row.id;
  tableFieldForm.pid = row.pid;
  tableFieldForm.columnName = row.columnName;
  tableFieldForm.comments = row.comments;
  tableFieldForm.dataType = row.dataType;
  tableFieldForm.columnId = row.columnId;
  tableFieldForm.isShow = row.isShow;
  tableFieldForm.isEdit = row.isEdit;
  tableFieldForm.sx = row.sx;
  tableFieldForm.classify = row.classify;
  tableFieldForm.aotuNum = row.aotuNum;
  tableFieldForm.prefixType = row.prefixType;
  tableFieldForm.prefix = row.prefix;
  tableFieldForm.infixType = row.infixType;
  tableFieldForm.infix = row.infix;
  tableFieldForm.suffixType = row.suffixType;
  tableFieldForm.suffix = row.suffix;
  tableFieldForm.expression = row.expression;
  tableFieldForm.dict = row.dict;
  tableFieldForm.correField = row.correField;
}

// 中间设计模式 设置字段
function setTableColumnDialog() {
  proxy.$nextTick(() => {
    getTableColumns();
  });
  showTableColumnDialog.value = true;
}

// 获取的所有设置字段
function getTableColumns() {
  tableColumnList.length = 0;
  setFieldsLoading.value = true;
  const url = '/api/sys/basDictTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { tableName: sltTable.code }
    })
    .then((res: any) => {
      tableColumnList.push(...res.data);
      setFieldsLoading.value = false;
    })
    .catch((err: any) => {
      setFieldsLoading.value = false;
      VxeMessage('获取设置字段失败', VxeNotifyType.error);
    });
}

// 设置字段弹框 字段属性复选框
function checCheckboxkMethod2({ row }: any) {
  const obj = dictTableFieldList.filter((p: any) => {
    return p.columnName == row.columnName;
  });
  return obj.length == 0;
}
// 设置字段弹框 字段属性复选框 设置
function showCheckboxkMethod2({ row }: any) {
  const obj = dictTableFieldList.filter((p: any) => {
    return p.columnName == row.columnName;
  });
  return obj.length == 0;
}

// 设置字段弹框里的保存
function saveBatchTableField() {
  const selectRows = (proxy.$refs.tableColumnRef as any).getCheckboxRecords();
  let fieldList = [];
  for (const sltRow of selectRows) {
    const field = {
      pid: sltTable.id,
      columnName: sltRow.columnName,
      comments: sltRow.comments,
      dataType: sltRow.dataType,
      columnId: sltRow.columnId,
      isShow: '0',
      isEdit: '1',
      sx: sltRow.columnId
    };
    fieldList.push(field);
  }
  const url = '/api/sys/basDictTableField/saveBatchTableField';
  const obj = {
    fieldList: fieldList
  };
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      VxeMessage('保存设置字段成功', VxeNotifyType.success);
      showTableColumnDialog.value = false;
      getDictTableFieldAndTableDataList();
    })
    .catch((err: any) => {
      VxeMessage('保存设置字段异常', VxeNotifyType.error);
    });
}
// 设置字段弹框里的取消
function closeTableColumnDialog() {
  showTableColumnDialog.value = false;
}

// 设计模式 最上层的保存
async function saveDictTableFieldList() {
  saveFieldsLoading.value = true;
  // 获取表格实例
  let $Xtable = proxy.$refs.dictTableFieldRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });
    if (updateRecords.length === 0) {
      return;
    }
    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let roleAddParam = e;
      proxy.$http
        .post('/api/sys/basDictTableField/editDictTableField', roleAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改字段成功', VxeNotifyType.success);
            saveFieldsLoading.value = false;
          } else {
            VxeMessage('修改字段失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改字段异常', VxeNotifyType.error);
          saveFieldsLoading.value = false;
        });
    });
    setTimeout(() => {
      getDictTableFieldAndTableDataList(); //重新获取设计模式的字段数据+预览模式表格值
    }, 500);
  } else {
    return;
  }
}

// 设计模式字段 当前行的删除
function deleteDictTableField(row: any) {
  proxy
    .$confirm('确定删除此字段设置？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/basDictTableField/deleteDictTableField';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          getDictTableFieldAndTableDataList();
          VxeMessage('删除字段设置成功', VxeNotifyType.success);
        } else {
          VxeMessage('删除字段设置失败', VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 改变设计模式的组件类型 3选1
function changeCorrection(item: any) {
  // item == dictForm.classify ? (dictForm.classify = '') : (dictForm.classify = item);
  // console.log(dictForm);
  if (item == tableFieldForm.classify) {
    tableFieldForm.classify = '';
  } else {
    tableFieldForm.classify = item;
  }
}

//获取设计模式表单的选择表达式
function getCyhsDictList() {
  cyhsDictList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { code: 'zdcyhs' } })
    .then((res: any) => {
      cyhsDictList.push(...res.data);
    })
    .catch((err: any) => {});
}
// 获取设计模式表单的选择字典
function findAllDictList() {
  dictAllList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDict/findDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { grade: 0 } })
    .then((res: any) => {
      dictAllList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

// 设计模式最右侧的表单保存
function saveTableField() {
  proxy.$http
    .post('/api/sys/basDictTableField/editDictTableField', tableFieldForm)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('修改属性成功', VxeNotifyType.success);
        getDictTableFieldAndTableDataList();
      } else {
        VxeMessage('修改属性失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('修改属性异常', VxeNotifyType.error);
    });
}

// 预览模式 添加数据弹框
function addTableDataDialog() {
  for (const obj of dictTableFieldList) {
    dataForm[obj.columnName] = '';
  }
  showDataDialog.value = true;
}

// 预览模式 添加数据弹框取消
function closeDataDialog() {
  showDataDialog.value = false;
}

//  预览模式 添加数据弹框 保存
function saveTableData() {
  const columnValueList = [];
  for (const obj of dictTableFieldList) {
    const columnValue = {
      column: obj.columnName,
      value: dataForm[obj.columnName],
      columnType: obj.dataType,
      classify: obj.classify,
      prefixType: obj.prefixType,
      prefix: obj.prefix,
      infixType: obj.infixType,
      infix: obj.infix,
      suffixType: obj.suffixType,
      suffix: obj.suffix
    };
    columnValueList.push(columnValue);
  }

  const obj = { tableName: sltTable.code, list: columnValueList };
  const idValue = columnValueList.find((p: any) => p.column == 'ID');
  if (IsEmpty(idValue.value)) {
    proxy.$http
      .post('/api/sys/basDictTable/addTableData', obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          getDictTableFieldAndTableDataList();
          VxeMessage('添加数据成功', VxeNotifyType.success);
          showDataDialog.value = false;
        }
      })
      .catch((err: any) => {
        VxeMessage('添加数据失败', VxeNotifyType.error);
        showDataDialog.value = false;
      });
  } else {
    proxy.$http
      .post('/api/sys/basDictTable/editTableData', obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          getDictTableFieldAndTableDataList();
          VxeMessage('修改数据成功', VxeNotifyType.success);
          showDataDialog.value = false;
        }
      })
      .catch((err: any) => {
        VxeMessage('修改数据成功', VxeNotifyType.error);
        showDataDialog.value = false;
      });
  }
}

// 预览模式表格当前行 编辑小按钮
function editTableData(row: any) {
  for (const obj of dictTableFieldList) {
    dataForm[obj.columnName] = row[obj.columnName];
  }
  showDataDialog.value = true;
}

// 预览模式 当前行删除小按钮
function deleteTableData(row: any) {
  proxy
    .$confirm('确定删除此条数据？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const obj = { tableName: sltTable.code, map: row };
      const url = '/api/sys/basDictTable/deleteTableData';
      proxy.$http.post(url, obj).then((res: any) => {
        if (res.status.code === 1) {
          getDictTableFieldAndTableDataList();
          VxeMessage('删除数据成功', VxeNotifyType.success);
        } else {
          VxeMessage('删除数据失败', VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 自动生成
function getBdsResult(code: any, value: any, row: any) {
  const dict = dictTableFieldList.find((it: any) => it.classify == '2');
  const expression = dict.expression;
  row[dict.columnName] = funBdsJsResult(expression, value);
  //dictList.find((it) => it.classify == '2').correField == item.code
}

// 获取可选的字典
function getSecletDictDetailById(row: any) {
  selectDetailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: row.dict } })
    .then((res: any) => {
      selectDetailList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}

// 判断预览模式 添加/编辑数据弹框 标题
function titlePre() {}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#dictManage {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }
  // 最左侧动态字典表格
  .tableBox {
    height: calc(100% - 40px);
    .spanIcon {
      padding: 0.1em 0.5em !important;
    }
  }
  // 中间设计模式表格 预览模式表格
  .designTable,
  .previewTable {
    height: calc(100% - 40px);
    .spanIcon {
      padding: 0.1em 0.5em !important;
    }
  }
  // 设置字段弹框
  .designPane {
    .setFieldsDialog {
      height: 500px;
      .setFieldsFooter {
        // margin-top: 10px;
      }
    }
  }

  .previewPane {
    width: 68% !important;
    // 每个单元格左内边距
    :deep(.vxe-cell) {
      padding-left: 5px;
    }
  }
}
</style>
